package com.suxin.plugin.intergration.manager.loader;

import com.suxin.plugin.intergration.manager.loader.path.PluginClasspath;
import com.suxin.plugin.intergration.manager.plugin.PluginManager;
import com.suxin.plugin.intergration.manager.repository.filter.JarFileFilter;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author Tang
 * @classname BasePluginLoader
 * @description [  ]
 * @date 2022/7/3 21:38
 */
public class BasePluginLoader implements PluginLoader{

    PluginManager pluginManager;

    PluginClasspath pluginClasspath;

    public BasePluginLoader(PluginManager pluginManager,PluginClasspath pluginClasspath) {
        this.pluginManager = pluginManager;
        this.pluginClasspath = pluginClasspath;
    }

    @Override
    public ClassLoader loadPlugin(Path pluginPath) {
        // 创建类加载器
        PluginClassLoader classLoader = createPluginClassLoader(pluginPath);
        // 加载class
        loadClasses(pluginPath,classLoader);
        // jar包加载
        loadJars(pluginPath, classLoader);
        return classLoader;
    }

    /**
     * 创建加载器
     * @param pluginPath
     * @return
     */
    private PluginClassLoader createPluginClassLoader(Path pluginPath) {
        return new PluginClassLoader(getClass().getClassLoader());
    }

    /**
     * 指定位置加载 jar
     * @param pluginPath
     * @param classLoader
     */
    private void loadJars(Path pluginPath, PluginClassLoader classLoader) {
        for (String jarsDirectory : pluginClasspath.getJarsDirectories()) {
            File[] files = pluginPath.resolve(jarsDirectory).toFile()
                    .listFiles(new JarFileFilter());
            for (File jar : files) {
                classLoader.addFile(jar);
            }
        }
    }

    private void loadClasses(Path pluginPath, PluginClassLoader classLoader) {

    }

    @Override
    public boolean isApplicable(Path pluginPath) {
        return Files.exists(pluginPath);
    }
}